package com.mouse.damo.service;

public class CustomService {
    /**
     * 轮训执行
     *
     * @param timeout     过期时间（s）
     * @param implService 轮训的方法。返回true，处理成功；返回false，处理不成功，继续执行。
     * @return 返回处理结果。返回true，执行成功；返回false，处理失败，处理超时
     */
    public boolean loop(long timeout, ImplService implService) {
        long t1 = System.currentTimeMillis();
        boolean result = false;
        while (true) {
            boolean actionFlag = implService.loopImpl();
            if (actionFlag) {
                result = true;
                break;
            }
            if (System.currentTimeMillis() - t1 > timeout * 1000) break;
        }
        System.out.println("轮训时间：" + (System.currentTimeMillis() - t1) + "毫秒");
        System.out.println("轮训结果：" + result);
        return result;
    }

    public void loopActin(long timeoutMil, ImplService implService) {
        long t1 = System.currentTimeMillis();
        boolean result = false;
        while (true) {
            boolean actionFlag = implService.loopImpl();
            if (actionFlag) {
                result = true;
                break;
            }
            if (System.currentTimeMillis() - t1 > timeoutMil) break;
        }
        System.out.println("轮训时间：" + (System.currentTimeMillis() - t1) + "毫秒");
        System.out.println("轮训结果：" + result);
    }

    /**
     * 轮训执行
     *
     * @param num         上限次数（s）
     * @param implService 轮训的方法。返回true，处理成功；返回false，处理不成功，继续执行。
     * @return 返回处理结果。返回true，执行成功；返回false，处理失败，处理超时
     */
    public boolean loopNum(long num, ImplService implService) {
        long t1 = System.currentTimeMillis();
        int i = 0;
        boolean result = false;
        while (true) {
            boolean actionFlag = implService.loopImpl();
            if (actionFlag) {
                result = true;
                break;
            }
            if (num >= i) break;
            i++;
        }
        System.out.println("轮训时间：" + (System.currentTimeMillis() - t1) + "毫秒");
        System.out.println("轮训结果：" + result);
        return result;
    }


    public Point loopPoint(long timeout, PointImplService implService) {
        long t1 = System.currentTimeMillis();
        Point point = new Point(-1, -1, -1);
        while (true) {
            Point point2 = implService.loopImpl();
            try {
                Thread.sleep(50);
            }catch (Exception e){

            }
            if (point2.getState() != -1) {
                point = point2;
                break;
            }
            if (System.currentTimeMillis() - t1 > timeout * 1000) break;
        }
        System.out.println("轮训时间：" + (System.currentTimeMillis() - t1) + "毫秒");
        return point;
    }
}
